<template>
    <a-row :gutter="16" style="padding: 15px 15px 0 15px;height: 100%;">
        <!--        展示部门列表-->
        <a-col :span="12">
            <div style="background: #fff;width: 100%;height: 100%;padding: 15px;overflow-y: auto">
                <a-button type="primary" @click="openAddModal">新增</a-button>
                <a-list
                        item-layout="horizontal"
                        size="large"
                        :data-source="departmentList"
                >
                    <template #header>
                        <a-input-search
                                v-model:value="departmentName"
                                style="margin-top: 10px"
                                placeholder="按部门名称搜索..."
                                enter-button
                                @search="onSearch"
                        />
                    </template>
                    <template #renderItem="{ item, index }">
                        <a-list-item>
                            <template #actions>
                                <a-button type="primary" @click="getDeptInfo(item,index)">编辑</a-button>
                            </template>
                            <a-list-item-meta>
                                <template #title>
                                    {{ item.name }}({{item.code}})
                                    <a-tag v-if="activeIndex == index" color="processing">
                                        <template #icon>
                                            <sync-outlined :spin="true"/>
                                        </template>
                                    </a-tag>
                                </template>
                                <template #description>{{item.remark}}</template>
                            </a-list-item-meta>
                            <div>
                                电话：{{item.tel}}
                            </div>
                        </a-list-item>
                    </template>
                    <template #footer>
                        <a-config-provider :locale="locale">
                            <a-pagination style="text-align: right"
                                          v-model:current="pagination.current"
                                          v-model:pageSize="pagination.pageSize"
                                          show-quick-jumper
                                          show-size-changer
                                          :total="pagination.total"
                                          :show-total="total => `总 ${total} 条数据`"
                                          :page-size-options="pageSizeOptions"
                                          @change="onChange"/>
                        </a-config-provider>
                    </template>
                </a-list>
            </div>
        </a-col>
        <!--        部门具体信息-->
        <a-col :span="12">
            <div style="width: 100%;height: 100%;overflow-y: auto;background: #fff;">
                <a-card v-if="JSON.stringify(deptInfo) != '{}'"
                        :tab-list="tabList"
                        :active-tab-key="key"
                        @tabChange="onTabChange">
                    <template v-if="key === 'deptInfo'">
                        <a-form
                                :model="deptInfo"
                                :label-col="{ span: 4 }"
                                :wrapper-col="{ span: 20 }"
                                autocomplete="off">
                            <a-form-item label="部门ID">
                                <a-input v-model:value="deptInfo.id" disabled/>
                            </a-form-item>
                            <a-form-item label="部门名称" v-bind="deptRef.validateInfos.name">
                                <a-input v-model:value="deptInfo.name"/>
                            </a-form-item>
                            <a-form-item label="部门编号">
                                <a-input v-model:value="deptInfo.code" disabled/>
                            </a-form-item>
                            <a-form-item label="部门领导" v-bind="deptRef.validateInfos.leader">
                                <a-select
                                        ref="select"
                                        v-model:value="deptInfo.leader"
                                        placeholder="请选择领导人"
                                        :options="userList"
                                        :field-names="{label: 'username', value: 'id'}"
                                ></a-select>
                            </a-form-item>
                            <a-form-item label="部门电话" v-bind="deptRef.validateInfos.tel">
                                <a-input v-model:value="deptInfo.tel"/>
                            </a-form-item>
                            <a-form-item label="部门邮箱" v-bind="deptRef.validateInfos.email">
                                <a-input v-model:value="deptInfo.email"/>
                            </a-form-item>
                            <a-form-item label="部门描述">
                                <a-textarea
                                        v-model:value="deptInfo.remark"
                                        :rows="4"/>
                            </a-form-item>
                        </a-form>
                    </template>
                    <template #actions>
                        <div v-if="key === 'deptInfo'" style="text-align: right;padding-right: 15px">
                            <a-space>
                                <a-button type="default" @click="deptInfo = JSON.parse(JSON.stringify(deptInfoTemp))">
                                    重置
                                </a-button>
                                <a-button type="primary" @click="UpdateDeptInfo">保存</a-button>
                            </a-space>
                        </div>
                    </template>
                </a-card>
                <a-empty v-else>
                    <template #description>
                        <span>暂未选择部门</span>
                    </template>
                </a-empty>
            </div>
        </a-col>
    </a-row>

    <a-modal v-model:visible="modalVisible" title="新增部门" @ok="addDeptOk">
        <a-form
                :model="addDeptData"
                :label-col="{ span: 6 }"
                :wrapper-col="{ span: 18 }"
                autocomplete="off">
            <a-form-item label="部门名称" v-bind="addDeptRef.validateInfos.name">
                <a-input v-model:value="addDeptData.name"/>
            </a-form-item>
            <a-form-item label="部门领导" v-bind="addDeptRef.validateInfos.leader">
                <a-select
                        ref="select"
                        v-model:value="addDeptData.leader"
                        placeholder="请选择领导人"
                        :options="userList"
                        :field-names="{label: 'username', value: 'id'}"
                ></a-select>
            </a-form-item>
            <a-form-item label="部门电话" v-bind="addDeptRef.validateInfos.tel">
                <a-input v-model:value="addDeptData.tel"/>
            </a-form-item>
            <a-form-item label="部门邮箱" v-bind="addDeptRef.validateInfos.email">
                <a-input v-model:value="addDeptData.email"/>
            </a-form-item>
            <a-form-item label="部门描述">
                <a-textarea
                        v-model:value="addDeptData.remark"
                        :rows="4"/>
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script>
    import {ref, onMounted} from 'vue'
    import axios from 'axios'
    import {Form, message} from 'ant-design-vue'
    import {SyncOutlined} from '@ant-design/icons-vue'
    import zhCN from 'ant-design-vue/lib/locale-provider/zh_CN'

    export default {
        name: "Department",
        components: {
            SyncOutlined
        },
        setup() {
            const locale = zhCN
            const tabList = [
                {
                    key: 'deptInfo',
                    tab: '基本信息',
                },
            ];
            const key = ref('deptInfo');
            const departmentList = ref([])
            const deptInfo = ref({
                name: '',
                leader: undefined,
                tel: '',
                email: ''
            })
            const departmentName = ref()
            const addDeptData = ref({
                name: '',
                leader: undefined,
                tel: '',
                email: ''
            })
            const useForm = Form.useForm
            const addDeptRef = useForm(addDeptData, {
                name: [{required: true, message: '请输入部门名称', trigger: ['submit', 'change']}],
                leader: [{required: true, message: '请选择部门领导', trigger: ['submit', 'change']}],
                tel: [{required: true, message: '电话号码不能为空', trigger: ['submit', 'change']},
                    {
                        pattern: /^(0\d{2,3})-?(\d{7,8})$/,
                        message: '电话号码非法',
                        trigger: ['submit', 'change']
                    }],
                email: [{required: true, message: '邮箱不能为空', trigger: ['submit', 'change']},
                    {pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: '邮箱非法', trigger: ['change']}],
            })

            const deptRef = useForm(deptInfo, {
                name: [{required: true, message: '请输入部门名称', trigger: ['submit', 'change']}],
                leader: [{required: true, message: '请选择部门领导', trigger: ['submit', 'change']}],
                tel: [{required: true, message: '电话号码不能为空', trigger: ['submit', 'change']},
                    {
                        pattern: /^(0\d{2,3})-?(\d{7,8})$/,
                        message: '电话号码非法',
                        trigger: ['submit', 'change']
                    }],
                email: [{required: true, message: '邮箱不能为空', trigger: ['submit', 'change']},
                    {pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: '邮箱非法', trigger: ['change']}],
            })
            const deptInfoTemp = ref({})
            const modalVisible = ref(false)
            const userList = ref([])
            const activeIndex = ref(-1)

            const pagination = ref({
                current: 1,
                pageSize: 5,
            })
            const pageSizeOptions = ref(['5', '10', '20', '30', '50', '100'])

            const onTabChange = (value) => {
                key.value = value
            }

            const onSearch = (pageNum) => {
                activeIndex.value = -1
                deptInfoTemp.value = {}
                deptInfo.value = {}
                pagination.value.current = pageNum == 1 ? 1 : pagination.value.current
                axios.get('/department/queryPageByCondition', {
                    params: {
                        pageNum: pagination.value.current,
                        pageSize: pagination.value.pageSize,
                        departmentName: departmentName.value
                    }
                }).then(rs => {
                    console.log("查找结果：", rs)
                    departmentList.value = rs.data.records
                    pagination.value.total = rs.data.total
                })
            }

            const onChange = (pageNum, pageSize) => {
                pagination.value.current = pageNum
                pagination.value.pageSize = pageSize
                onSearch()
            }

            const getDeptInfo = (obj, index) => {
                deptRef.resetFields()
                activeIndex.value = index
                getThisUserAndNotAssociateUser(obj.leader)
                deptInfoTemp.value = JSON.parse(JSON.stringify(obj))
                deptInfo.value = JSON.parse(JSON.stringify(deptInfoTemp.value))
            }

            const getThisUserAndNotAssociateUser = (leaderId) => {
                axios.get('user/queryThisUserAndNotAssociateUser', {
                    params: {
                        userId: leaderId
                    }
                }).then(rs => {
                    userList.value = rs.data
                })
            }

            const openAddModal = () => {
                addDeptRef.resetFields()
                getThisUserAndNotAssociateUser()
                modalVisible.value = true
            }

            const addDeptOk = () => {
                addDeptRef.validate().then(() => {
                    axios.post('department/save', addDeptData.value).then(rs => {
                        if (rs.code == 200) {
                            message.success("新增部门成功")
                            onSearch(1)
                            modalVisible.value = false
                        } else {
                            message.error(rs.message)
                        }
                    })
                }).catch(() => {
                    console.log("校验失败")
                })

            }

            const UpdateDeptInfo = () => {
                deptRef.validate().then(() => {
                    axios.put('department/update', deptInfo.value).then(rs => {
                        if (rs.code == 200) {
                            message.success(deptInfo.value.name + "信息更新成功")
                            onSearch()
                        } else {
                            message.error(rs.message)
                        }
                    })
                }).catch(() => {
                    console.log("校验失败")
                })
            }

            onMounted(() => {
                onSearch()
            })

            return {
                departmentList,
                tabList,
                key,
                onTabChange,
                onSearch,
                departmentName,
                pagination,
                pageSizeOptions,
                onChange,
                locale,
                openAddModal,
                modalVisible,
                addDeptOk,
                addDeptData,
                userList,
                deptInfo,
                deptInfoTemp,
                getDeptInfo,
                activeIndex,
                UpdateDeptInfo,
                addDeptRef,
                deptRef
            }
        }
    }
</script>

<style>
    .ant-card-body {
        height: calc(100% - 57px - 57px);
    }
</style>